<?php
namespace LaneWeChat\Core;
include __DIR__ . '/../db.php';
class Common{

    const TEMP_MSG_YZM = '您的验证码是：【%s】。请不要把验证码泄露给其他人。如非本人操作，可不用理会！';

    const MSG_URL = 'http://sms.106jiekou.com/utf8/sms.aspx';

    const MSG_USERNAME = 'yuen0078';

    const MSG_PASSWORD = 'fx990516___';

    /**
     * @param $mobile
     * @param $code
     * @return bool
     */
    public static function sendMsg( $mobile , $code ){
        header("Content-Type: text/html; charset=utf-8");
        $content = sprintf( self::TEMP_MSG_YZM , $code );
        //替换成自己的测试账号,参数顺序和wenservice对应
        $post_data = sprintf( "account=%s&password=%s&mobile=%s&content=%s" ,
            self::MSG_USERNAME ,
            self::MSG_PASSWORD ,
            $mobile ,
            rawurlencode($content)
        ) ;
        $result = Curl::callWebServer( self::MSG_URL , $post_data , 'post' );
        return $result == 100;
    }

    /**
     * 获取当前用户信息
     * @param string $callback
     * @return JSON
     */
    public static function getCurrentUserInfo( $callback = '' ){
		//$_SESSION['openid'] = null;
        $openid = isset( $_SESSION['openid'] ) ? trim( (string)$_SESSION['openid'] ) : null;
        if( empty( $openid ) || strlen( $openid ) <= 0 ){
            $code = $_GET['code'];
            if( empty( $code ) ){
                header( 'Location: info.php?backUrl='.$callback );exit;
            }
            $result = \LaneWeChat\Core\WeChatOAuth::getAccessTokenAndOpenId($code);
			if( !isset( $result['openid'] ) ) $result['openid'] = 0;
            $openid = $_SESSION['openid'] = $result['openid'];
        }
        $data = (array)\Mysql::getInstance()->query( 'select * from `lw_users` where openid="'.$openid.'" limit 0 ,1 ')
            ->fetch_array();
		
        $info = \LaneWeChat\Core\UserManage::getUserInfo( $openid );
		if(isset($data[0]))
			$data = array_merge( (array)$data[0] , (array)$info );
		else{
			$data = $info;
		}
        return $data;
    }
	
	 /**
     * 下单
     * @param array $post_data
     */
	public static function createOrder($openid,$price,$goodsname){
		$result = self::getLogin( $openid );
		if( empty( $result ) || empty( $result['sessionId'] ) ){
			self::outPutJson( 3 , 'failed' , '' );
		}
		$url = API_HOST . 'MallVipSale.aspx?sid='.$result['sessionId'];
        $url .= '&VipId=' . $result['VipId'] . '&TotalAmt='.$price;
        $url .= '&Goods_Name='.$goodsname.'&Price='.$price.'&Qty=1';
        $output = $oldMessage =  file_get_contents($url);
		file_put_contents("order.txt",$url . json_encode($result));
		$output = json_decode( $output , true );
		if( empty( $output ) || ( isset($output['status']) && $output['status'] != 0 ) ){
            self::outPutJson(4,[],'网络错误,支付失败！'.$output['message']);
        }
		if( !isset($output['status']) ){
			 self::outPutJson(6,[],'网络错误,支付失败！');
		}
		self::outPutJson(0,[],'');
	}

    /**
     * 开卡
     * @param array $post_data
     */
    public static function openCard( $post_data = array() ){
        $url = API_HOST . 'QueryVipBalanceInfo.aspx';
        unset( $post_data['avatar'] , $post_data['yzm'] , $post_data['password1'], $post_data['password'] );
        $post_data['startdate'] = date('Y-m-d');
        $post_data['enddate'] = date('Y-m-d',time()+10*365*86400);
        $post_data['remark'] = '微信开卡用户';
		if(empty($post_data['card'])){
			unset($post_data['card']);
		}
        $url .= '?Type=3&' . http_build_query( $post_data );
        $output = $oldMessage =  file_get_contents($url);
		file_put_contents("opencard.txt",$url . json_encode($output));
        $output = json_decode( $output , true );
		
        if( !empty( $output ) && is_array( $output ) && $output['status'] == 0 ){
			\Mysql::getInstance()->delete('lw_users','openid="'.$_POST['code'].'"');
            \Mysql::getInstance()->insert(
                'lw_users',
                'openid,add_time,name,headimgurl,company,staff_code,identity',
                '"'.$_POST['code'] . '",' . time() . ',"' . $_POST['name'] . '"'. ',"' . $_POST['avatar'] . '"'
				. ',"' . $_POST['company'] . '"'. ',"' . $_POST['workNo'] . '"'. ',"' . $_POST['identy'] . '"'
            );
            \LaneWeChat\Core\Common::alert('开卡或者绑卡成功','qrcode.php');
        }
        else{
            \LaneWeChat\Core\Common::alert('开卡或绑卡失败！'.$output['message']);
        }
    }

    /**
     * 挂失
     * @param string $openid
     */
    public static function cardLoss( $openid , $type ){
        $result = self::getLogin( $openid );
		if( empty( $result ) || empty( $result['sessionId'] ) ){
			self::outPutJson( 2 , 'failed' , '' );
		}
        //挂失
        $url = API_HOST.'QueryVipBalanceInfo.aspx';
        $url .= '?Type=4&isReSendCard='.$type.'&sid='.$result['sessionId'].'&vipId='.$result['VipId'].'&code='.$openid;
        $info = file_get_contents( $url );
        $info = json_decode( $info , true );
        if( $info['status'] == 0 && $type == 'N' ){
            \Mysql::getInstance()->delete('lw_users','openid="'.$openid.'"');
        }
        self::outPutJson( $info['status'] , $info , '' );
    }

    /**
     * @param $openid
     * @param $oldPass
     * @param $newPass
     */
    public static function changePass( $openid , $oldPass , $newPass ){
        $result = self::getLogin( $openid );
        //挂失
        $url = API_HOST.'Login.aspx';
        $url .= '?Type=5&sid='.$result['sessionId'].'&vipId='.$result['VipId'].'&code='.$result['cardno'];
        $url .= '?oldPwd='.$oldPass.'&newPwd='.$newPass;
        $info = file_get_contents( $url );
        $info = json_decode( $info , true );
        self::outPutJson( 0 , $info , '' );
    }

    /**
     * 获取当前卡信息
     * @param string $callback
     * @return JSON
     */
    public static function getCurrentCardInfo( $openid ){
        $result = self::getLogin( $openid );
        if( empty( $result ) ){
			$_SESSION['openid'] = null;
            self::alert("暂未开卡～，请先前去开卡",'/app/index.php?i=2&c=entry&do=orderdetail&m=weisrc_dish&otherurl=opencard');
        }
        $url = API_HOST.'QueryVipBalanceInfo.aspx';
        $url .= '?Type=2&sid='.$result['sessionId'].'&VipId='.$result['VipId'];
        $info = file_get_contents( $url );
        $info = json_decode( $info , true );
        if( $info['status'] != 0 ){
            self::alert("卡已挂失或者退掉，请重新开卡~",'opencard.php');
        }
        return $info['data'];
    }

    /**
     * @param $openid
     * @param $id
     * @param $start
     * @param $end
     * @return mixed
     */
    public static function getReport( $openid , $id , $start , $end ){
        $result = self::getLogin( $openid );
	
        $url = API_HOST.'ReportMethod.aspx?type='.$id;
        $url .= '&StartDate='.$start.'&EndDate='.$end.'&sid='.$result['sessionId'];
        $url .= '&code='.$openid;
        $list = file_get_contents( $url );
        $list = json_decode( $list , true );
        return $list;
    }

    /**
     * @param $openid
     * @param $orderNo
     * @return mixed
     */
    public static function getReportDetail( $openid , $orderNo ){
        $result = self::getLogin( $openid );
        $url = API_HOST.'ReportMethod.aspx?type=Rpt_Sale_Detail';
        $url .= '&sid='.$result['sessionId'];
        $url .= '&orderNo='.$orderNo;
        $list = file_get_contents( $url );
        $list = json_decode( $list , true );
        return $list;
    }

    /**
     * @param $openid
     * @param $sid
     * @param $vipid
     * @return mixed|string
     */
    public static function getReportList( $openid , $sid , $vipid ){
        $url = API_HOST.'ReportMethod.aspx?type=CKIN';
        $url .= '&vipid='.$vipid.'&code='.$openid.'&sid='.$sid;
        $list = file_get_contents( $url );
        $list = json_decode( $list , true );
        return $list;
    }

    /**
     * 登录饭卡
     * @param $openid
     * @return array|mixed|string
     */
    public static function getLogin( $openid ){
		if(isset($_SESSION[$openid])){
			//return $_SESSION[$openid];
		}
        $url = API_HOST.'Login.aspx';
        $url .= '?Type=1&userno=' . $openid . '&vipid=';
        $result = file_get_contents( $url );
        $result = json_decode( $result , true );
        if( !empty( $result ) && is_array( $result ) && $result['status'] == 0 ){
			//$_SESSION[$openid] = $result;
            return $result;
        }
        return array();
    }

    /**
     * JS支付参数
     * @param $openid
     * @return array|mixed|string
     */
    public static function getJsPay( $openid , $money , $num ){
        include_once __DIR__ . '/../WeiXinPay.php';
        $money = floatval( $money );
        $num = intval( $num );
        $money = $money*$num;
        $orderId = time() . rand( 100 , 999 );
        //添加数据库
        \Mysql::getInstance()->insert(
            'lw_recharge_log',
            'order_id,money,openid,add_time',
            '"' . $orderId . '",' . $money . ',"' . $openid . '",' . time()
        );
		try{
        //添加数据库
        $jsParams = \app\services\weixin\pay\WeiXinPay::getInstance()
            ->setOpenId( $openid )
            ->getJsApiParam( $money * 100 , $orderId , '鹏企在线充值' , 101 );
			file_put_contents('text.txt',json_encode($jsParams));
		}
			catch( Exception $e ){
				 self::outPutJson(
            1 ,
            $e->getMessage()
        );
			}
        self::outPutJson(
            0 ,
            array(
                'address' => $jsParams['address'],
                'js' => $jsParams['js'],
            )
        );
    }

    /**
     * 支付
     * @param $orderId
     * @return array|mixed|string
     */
    public static function recharge( $orderId ){
		$order = (array)\Mysql::getInstance()->query( 'select openid,money from lw_recharge_log where order_id="' . $orderId . '" and status = 0 ')
            ->fetch_array();
        //查找订单 更新订单状态
		if( count( $order ) > 0 ){
			$openid = $order[0]['openid'];
			$result = self::getLogin( $openid );
			$vipid = $result['VipId'];
			$sid = $result['sessionId'];
			$url = API_HOST.'MallRecharge.aspx';
			$url .= '?sid='.$sid.'&vipid='.$vipid.'&SumCash='.($order[0]['money']*100).'&code='.$openid.'&type=1';
			//echo $url ;
			file_get_contents( $url );
			file_put_contents( 'recharge.txt' , $url );

			//设置支付时间
			\Mysql::getInstance()->query('update lw_recharge_log set status = 1 where order_id="' . $orderId . '"' );
		}
       
    }


    /**
     * 单位列表
     * @return array
     */
    public static function getCompany(){
        return \Mysql::getInstance()->query('select * from lw_adconfig')
            ->fetch_array();
    }

    /**
     * @param int $error
     * @param array $data
     * @param string $msg
     */
    public static function outPutJson( $error = 0 , $data = array() , $msg = '' ){
        exit(
            json_encode(
                array(
                    'error' => $error,
                    'msg' => $msg,
                    'data' => $data
                )
            )
        );
    }

    /**
     * @param $msg
     * @param string $url
     */
    public static function alert( $msg , $url = '' ){
        if( empty( $url ) ){
            $link = 'history.go(-1);';
        }
        else{
            $link = 'window.location.href="'.$url.'";';
        }
        exit('<meta charset="UTF-8" /><script>alert("'.$msg.'");'.$link.'</script>');
    }

}

?>